package cn.lbz.Login;

import cn.lbz.Filter.AuthFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.io.Serial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class LoginServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1198763434511986380L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
        boolean b;
        //根据标示名获取JSP文件中表单所包含的参数
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        String code = request.getParameter("code");

        HttpSession session = request.getSession(true);
        String validateCode = (String) session.getAttribute(AuthFilter.LOGIN_VALIDATE_CODE);
        if (validateCode == null || !validateCode.equalsIgnoreCase(code)) {
            response.sendRedirect("/lbz-javaweb/login.html");
            return;
        }

        b=isuserlogin(user,password);//使用模型对账号和密码进行验证，返回一个boolean类型的对象
        if(b){
            session.setAttribute(AuthFilter.LOGIN_STATUS, Boolean.TRUE);
            response.sendRedirect("/lbz-javaweb/admin/main.jsp");

            System.out.println("登陆成功");
        }
        else {
            response.sendRedirect("/lbz-javaweb/login.html" );

            System.out.println("登陆失败");
        }
    }

    private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DB_URL    = "jdbc:mysql://127.0.0.1:3306/user";
    private static final String DB_USER   = "root";
    private static final String DB_PASS   = "20020111Zhao";

    private boolean isuserlogin(String user, String password) {
        boolean isValid = false;
        String sql = "select * from user where uname='" + user + "' and password='" + password + "'";
        try {
            Class.forName(DB_DRIVER);
            Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(sql);
            System.out.println(sql);
            if (rs.next()) {
                isValid = true;
            }
            rs.close();
            stm.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断用户名以及密码是否与设定相符
        return isValid;
    }
}
